<!-- 任务页面 - 显示任务列表和日历 -->
<template>
  <view class="task-page">
    <!-- 导航栏 -->
    <NavBar title="任务管理" showBack="false" showSearch="true">
      <view class="nav-right-actions" slot="right">
        <view class="view-toggle-container" @click="toggleCalendarView">
          <uni-icons type="list" size="20" color="white" class="view-toggle-icon"></uni-icons>
          <text class="view-toggle-text">{{ viewType === 'day' ? '月' : '日' }}</text>
        </view>
        <view class="today-btn" @click="goToCurrentMonth">
          <uni-icons type="calendar" size="20" color="white"></uni-icons>
          <text class="today-btn-text">当月</text>
        </view>
      </view>
    </NavBar>
    
    <!-- 主内容区域 -->
    <view class="main-content">
      <!-- 日期选择器 -->
      <view class="date-section">
        <text class="current-date">{{ formattedSelectedDate }}</text>
        <uni-icons type="calendar" size="20" color="#4CAF50" class="calendar-icon" @click="toggleCalendar"></uni-icons>
      </view>
      
      <!-- 星期显示行 - 始终可见 -->
    <view class="weekday-display">
      <text class="weekday-item" 
            v-for="(weekday, index) in weekdays" 
            :key="weekday"
            :class="{
              'selected': isSelectedWeekday(index),
              'today': isTodayWeekday(index)
            }"
            @click="onWeekdayClick(index)">
        {{ weekday }}
        <view class="weekday-today-mark" v-if="isTodayWeekday(index)">今</view>
      </text>
    </view>
      
      <!-- 日历组件（可折叠） -->
      <view class="calendar-container" v-if="showCalendar">
        <Calendar 
          ref="calendar"
          :selectedDate="selectedDate"
          :tasks="allTasks"
          :viewType="viewType"
          @date-select="onDateSelect"
          @month-change="onMonthChange"
        ></Calendar>
      </view>
      
      <!-- 任务列表（按时间段分组） -->
      <view class="task-list">
        <!-- 上午任务 -->
        <div class="task-group">
          <div class="task-group-header morning">
            <uni-icons type="sunrise" size="18" color="#E64A19"></uni-icons>
            <text class="task-group-title">上午</text>
          </div>
          <div v-if="groupedTasks.morning.length > 0">
            <TaskItem 
              v-for="task in groupedTasks.morning" 
              :key="task.id" 
              :task="task"
              :timeSlot="'morning'"
              @toggle-completion="toggleTaskCompletion"
              @edit="editTask"
              @delete="deleteTask"
            ></TaskItem>
          </div>
        </div>
        
        <!-- 下午任务 -->
        <div class="task-group">
          <div class="task-group-header afternoon">
            <uni-icons type="sun" size="18" color="#FFEB3B"></uni-icons>
            <text class="task-group-title">下午</text>
          </div>
          <div v-if="groupedTasks.afternoon.length > 0">
            <TaskItem 
              v-for="task in groupedTasks.afternoon" 
              :key="task.id" 
              :task="task"
              :timeSlot="'afternoon'"
              @toggle-completion="toggleTaskCompletion"
              @edit="editTask"
              @delete="deleteTask"
            ></TaskItem>
          </div>
        </div>
        
        <!-- 晚上任务 -->
        <div class="task-group">
          <div class="task-group-header evening">
            <uni-icons type="moon" size="18" color="#673AB7"></uni-icons>
            <text class="task-group-title">晚上</text>
          </div>
          <div v-if="groupedTasks.evening.length > 0">
            <TaskItem 
              v-for="task in groupedTasks.evening" 
              :key="task.id" 
              :task="task"
              :timeSlot="'evening'"
              @toggle-completion="toggleTaskCompletion"
              @edit="editTask"
              @delete="deleteTask"
            ></TaskItem>
          </div>
        </div>
      </view>
    </view>
    
    <!-- 添加任务按钮 -->
    <view class="add-button" @click="navigateToAddTask">
      <text class="plus-symbol">+</text>
    </view>
  </view>
</template>

<script>
// 导入组件
import NavBar from '../../components/NavBar.vue'
import Calendar from '../../components/Calendar.vue'
import TaskItem from '../../components/TaskItem.vue'

export default {
  components: {
    NavBar,
    Calendar,
    TaskItem
  },
  data() {
    return {
      // 是否显示日历
      showCalendar: false,
      // 任务筛选器
      filter: 'all',
      // 星期列表
      weekdays: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      // 视图类型（'day' 或 'month'）
      viewType: 'day'
    }
  },
  computed: {
    // 从Vuex获取选中的日期
    selectedDate() {
      return this.$store.state.selectedDate
    },
    
    // 获取今天的日期
    today() {
      const date = new Date()
      return date.toISOString().split('T')[0]
    },
    
    // 获取选中日期对应的星期几
    selectedWeekday() {
      if (!this.selectedDate) return -1
      const date = new Date(this.selectedDate)
      return date.getDay()
    },
    
    // 获取今天对应的星期几
    todayWeekday() {
      const date = new Date()
      return date.getDay()
    },
    
    // 从Vuex获取所有任务
    allTasks() {
      return this.$store.state.tasks
    },
    
    // 获取选中日期的任务
    selectedDateTasks() {
      return this.$store.getters.selectedDateTasks
    },
    
    // 格式化选中的日期显示
    formattedSelectedDate() {
      const date = new Date(this.selectedDate)
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const weekdays = ['日', '一', '二', '三', '四', '五', '六']
      const weekday = weekdays[date.getDay()]
      
      // 如果是今天且是日视图，添加特殊标识
      if (this.viewType === 'day' && date.toISOString().split('T')[0] === this.today) {
        return `${month}月${day}日 星期${weekday} (今天)`
      }
      
      return `${month}月${day}日 星期${weekday}`
    },
    
    // 根据筛选条件获取任务
    filteredTasks() {
      let tasks = this.selectedDateTasks
      
      if (this.filter === 'pending') {
        tasks = tasks.filter(task => !task.isCompletedToday)
      } else if (this.filter === 'completed') {
        tasks = tasks.filter(task => task.isCompletedToday)
      }
      
      // 按时间排序
      return tasks.sort((a, b) => {
        return a.startTime.localeCompare(b.startTime)
      })
    },
    
    // 按时间段分组任务
    groupedTasks() {
      const morning = []
      const afternoon = []
      const evening = []
      
      this.filteredTasks.forEach(task => {
        const hour = parseInt(task.startTime.split(':')[0])
        
        if (hour >= 6 && hour < 12) {
          morning.push(task)
        } else if (hour >= 12 && hour < 18) {
          afternoon.push(task)
        } else {
          evening.push(task)
        }
      })
      
      return {
        morning,
        afternoon,
        evening
      }
    }
  },
  onLoad() {
    // 页面加载时，初始化日历选中日期
    if (this.$refs.calendar) {
      this.$refs.calendar.setSelectedDate(this.selectedDate)
      this.$refs.calendar.setTasks(this.allTasks)
    }
  },
  onShow() {
    // 页面显示时，刷新任务列表
    if (this.$refs.calendar) {
      this.$refs.calendar.setTasks(this.allTasks)
    }
  },
  methods: {
    // 判断是否是选中的星期几
    isSelectedWeekday(index) {
      return this.selectedWeekday === index
    },
    
    // 判断是否是今天对应的星期几
    isTodayWeekday(index) {
      // 只有在日视图下才显示今天标识
      return this.viewType === 'day' && this.todayWeekday === index
    },
    
    // 切换日历显示状态
    toggleCalendar() {
      this.showCalendar = !this.showCalendar
    },
    
    // 切换视图类型（日/月视图）
    toggleCalendarView() {
      this.viewType = this.viewType === 'day' ? 'month' : 'day'
      this.toggleCalendar() // 切换日历显示状态
    },
    
    // 切换到当前月
    goToCurrentMonth() {
      // 显示日历
      if (!this.showCalendar) {
        this.toggleCalendar()
      }
      
      // 如果在月视图下，直接滚动到当前月
      if (this.viewType === 'month') {
        // 重置选中的日期为今天
        this.$store.commit('setSelectedDate', new Date().toISOString())
        
        // 通知日历组件切换到当前月
        this.$emit('month-change', new Date().getMonth() + 1)
        
        // 滚动到当前月的位置
        if (this.$refs.calendar) {
          // 这里需要确保Calendar组件有滚动到当前月的方法
          this.$refs.calendar.scrollToCurrentMonth()
        }
      }
    },
    
    // 点击星期切换日期
    onWeekdayClick(index) {
      // 只有在日视图下才能点击星期切换日期
      if (this.viewType === 'day') {
        const today = new Date()
        const currentWeekday = today.getDay()
        const daysDiff = index - currentWeekday
        
        // 计算目标日期
        const targetDate = new Date()
        targetDate.setDate(today.getDate() + daysDiff)
        
        // 更新选中的日期
        this.$store.commit('setSelectedDate', targetDate.toISOString())
      }
    },
    
    // 选择日期
    onDateSelect(date) {
      const formattedDate = date.toISOString()
      this.$store.commit('setSelectedDate', formattedDate)
      // 关闭日历
      this.showCalendar = false
    },
    
    // 月份变化
    onMonthChange(date) {
      // 这里可以添加月份变化的处理逻辑
    },
    
    // 设置任务筛选条件
    setFilter(filter) {
      this.filter = filter
    },
    
    // 切换任务完成状态
    toggleTaskCompletion(taskId) {
      this.$store.commit('toggleTaskCompletion', taskId)
    },
    
    // 编辑任务
    editTask(task) {
      // 跳转到编辑任务页面，并传递任务数据
      uni.navigateTo({
        url: `/pages/editTask/editTask?id=${task.id}`
      })
    },
    
    // 删除任务
    deleteTask(taskId) {
      this.$store.commit('deleteTask', taskId)
      // 显示删除成功提示
      uni.showToast({
        title: '任务已删除',
        icon: 'success'
      })
    },
    
    // 跳转到添加任务页面
    navigateToAddTask() {
      uni.navigateTo({
        url: '/pages/addTask/addTask'
      })
    }
  }
}
</script>

<style scoped>
.task-page {
  padding-top: 88rpx; /* 导航栏高度 */
  min-height: 100vh;
  background-color: #F5F5F5;
}

.main-content {
  padding: 16px;
}

/* 日期选择区域 */
.date-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #E0E0E0;
}

/* 星期显示行 */
.weekday-display {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 5px 0;
  background-color: white;
  border-radius: 8px;
}

.weekday-item {
  font-size: 14px;
  color: #757575;
  width: 14%;
  text-align: center;
  padding: 8px 0;
  position: relative;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.weekday-item:active {
  background-color: #f0f0f0;
}

/* 选中日期的星期样式 */
.weekday-item.selected {
  background-color: #C8E6C9;
  color: #388E3C;
  font-weight: bold;
}

/* 今天的星期样式 */
.weekday-item.today {
  color: #4CAF50;
  font-weight: bold;
}

/* 今天标记 */
.weekday-today-mark {
  position: absolute;
  top: 2px;
  right: 5px;
  font-size: 10px;
  background-color: #FF9800;
  color: white;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.current-date {
  font-weight: bold;
  color: #333333;
  font-size: 16px;
}

.calendar-icon {
  cursor: pointer;
  color: #4CAF50;
  font-size: 18px;
}

/* 日历容器 */
.calendar-container {
  margin-bottom: 16px;
  padding: 10px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 任务列表 */
.task-list {
  margin-bottom: 100rpx; /* 为添加按钮留出空间 */
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-state text {
  margin-top: 20rpx;
  font-size: 28rpx;
}

/* 任务分组样式 */
.task-group {
  margin-bottom: 20rpx;
}

/* 任务分组标题 */
.task-group-header {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
  padding: 8rpx 16rpx;
  border-radius: 6px;
}

/* 任务分组标题文本 */
.task-group-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-left: 8rpx;
}

/* 上午分组样式 */
.task-group-header.morning {
  background-color: #FFEBEE;
  /* 浅红色背景，与深橙色主色调更协调 */
}

.task-group-header.morning .task-group-title {
  color: #E64A19;
}

/* 下午分组样式 */
.task-group-header.afternoon {
  background-color: #FFF8E1;
  /* 保持浅黄色背景，但与上午有明显区分 */
}

.task-group-header.afternoon .task-group-title {
  color: #FDD835;
}

/* 晚上分组样式 */
.task-group-header.evening {
  background-color: #E8EAF6;
}

.task-group-header.evening .task-group-title {
  color: #5E35B1;
}

/* 添加任务按钮 */
.add-button {
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #4CAF50;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
  z-index: 100;
}

.plus-symbol {
  color: white;
  font-size: 36px;
  font-weight: bold;
  line-height: 1;
}

/* 视图切换按钮样式 */
/* 导航栏右侧操作区 */
.nav-right-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.view-toggle-container {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 15px;
  background-color: rgba(255, 255, 255, 0.2);
  cursor: pointer;
  margin-right: 0;
}

/* 当月按钮 */
.today-btn {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 5px 10px;
  border-radius: 15px;
  cursor: pointer;
}

.today-btn-text {
  margin-left: 5px;
  color: white;
  font-size: 14px;
}

.view-toggle-text {
  color: white;
  font-size: 14px;
  margin-left: 4px;
}
</style>
